import _ from 'lodash';
import { message } from 'antd';
import { routerRedux } from 'dva/router';
import { matchDict } from '@/utils/utils';
import {
  getAdjAccuDetail,
  fetchAdjAccuDetail,
  getAdjAccuUpdateDetail,
  getSerConfigList,
  getAcountList,
  getInsGroupList,
  accuSubmit,
  updateAccuSubmit,
} from '@/services/adjusttask';

export default {
  state: {
    empNameList: [], // 单个调整雇员姓名
    // 调整信息
    updateBaseInfo: {}, // 基本信息
    updateInsIde: null, // 缴费人员类别
    updateAccuLocPkg: null, // 公积金组合
    updateAccuDecWage: null, // 公积金申报工资
    accuWageFlag: false, // 是否修改公积金申报工资
    insSetFlag: true, // 五险合不合一
    isAssSetFlag: '1', // 公积金工资分项:1是2否
    accuLocFlag: false, // 是否修改公积金组合
    insSerConfigFlag: '2', // 公积金组合是否使用服务配置
    serConfigList: [], // 服务配置列表
    accuPayWayList: [], // 公积金缴费方式
    accountList: [], // 缴费账户列表
    insGroupList: [], // 公积金组合列表
    insGroupData: [], // 公积金组合数据
    insList: [], // 险种集合
    payWay: null, // 缴费方式：1单立户  2大库
    isHasSingle: false, // 有无单立户
    isHasbigStore: false, // 有无大库
    sendId: null,
    beginDate: undefined,
    isSupplyRun: false, // 是否由供应商执行
  },
  effects: {
    // 获取是否进去下一步
    *fetchNextStep({ payload }, { call }) {
      const response = yield call(getAdjAccuDetail, payload);
      return response;
    },
    // 单个调整：获取公积金信息
    *fetchAdjAccuDetail({ payload }, { call, put, select }) {
      const response = yield call(
        payload.adjId ? getAdjAccuUpdateDetail : fetchAdjAccuDetail,
        payload
      );
      const dictCode = yield select(state => state.publicdata.dictCode);
      const insList = [];
      let isHasSingle = false;
      let isHasbigStore = false;
      const updateAccuLocPkg = [];
      if (response.success) {
        if (response.data.accuPayWayList) {
          const newInsPayWayList = [];
          if (dictCode.PAY_FEES_WAY.length) {
            isHasSingle = response.data.accuPayWayList.some(item => item === '1');
            isHasbigStore = response.data.accuPayWayList.some(item => item === '2');
            response.data.accuPayWayList.forEach(l => {
              newInsPayWayList.push({
                itemCode: l,
                itemName: matchDict(dictCode.PAY_FEES_WAY, l),
              });
            });
          }
          response.data.accuPayWayList = newInsPayWayList;
        }
        if (response.data.updateAccuLocPkg) {
          updateAccuLocPkg.push({
            ...response.data.updateAccuLocPkg,
            accoName: response.data.updateAccuLocPkg.accuAccoName || '',
            insGrpName: response.data.updateAccuLocPkg.accuGrpName || '',
          });
          if (dictCode.PAY_FEES_WAY.length) {
            updateAccuLocPkg.forEach(item => {
              insList.push(item.ass);
            });
          }
        }
        yield put({
          type: 'updateModelData',
          payload: {
            ...payload,
            insGroupData: _.cloneDeep(updateAccuLocPkg),
            ...response.data,
            updateAccuLocPkg,
            insSetFlag: response.data.updateBaseInfo && response.data.updateBaseInfo.insSetFlag,
            sendId: response.data.updateBaseInfo && response.data.updateBaseInfo.sendId,
            custId: response.data.updateBaseInfo && response.data.updateBaseInfo.custId,
            insList,
            isHasSingle,
            isHasbigStore,
            isSupplyRun:
              (response.data.updateBaseInfo && response.data.updateBaseInfo.execType === 2) ||
              false,
          },
        });
      } else {
        message.warning(response.message || '获取人员信息：服务端错误');
      }
    },

    // 获取服务配置列表
    *fetchSerConfigList({ call, put, select }) {
      const adjustInfo = yield select(state => state.adjustaccu);
      const { custId } = adjustInfo;
      const areaId = adjustInfo.updateBaseInfo.cityId;
      const kindList = [];
      adjustInfo.insList.forEach(item => {
        kindList.push({
          kind: item,
          areaId,
        });
      });
      const { quoId } = adjustInfo.updateBaseInfo;
      const response = yield call(getSerConfigList, { custId, kindList, quoId });
      if (response.success) {
        if (response.data && response.data.length) {
          yield put({
            type: 'updateModelData',
            payload: {
              serConfigList: response.data,
            },
          });
        } else {
          yield put({
            type: 'updateModelData',
            payload: {
              serConfigList: [],
            },
          });
          message.warning('该地区下未维护服务配置');
        }
      } else {
        message.warning(response.message || '获取服务配置列表：服务端错误');
      }
    },
    // 获取公积金账户列表
    // eslint-disable-next-line consistent-return
    *fetchAcountList(
      {
        payload: { payWay },
      },
      { call, put, select }
    ) {
      const adjustInfo = yield select(state => state.adjustaccu);
      const insKinds = [];
      const areaId = adjustInfo.updateBaseInfo.cityId;
      const { custId } = adjustInfo;
      const response = yield call(getAcountList, { custId, insKinds, areaId, payWay });
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'updateModelData',
            payload: {
              accountList: response.data,
            },
          });
          return response.data;
        }
        message.warning('该地区下未维护公积金账户');
      } else {
        message.warning(response.message || '获取公积金账户列表：服务端错误');
      }
    },

    // 获取公积金组合列表
    // eslint-disable-next-line no-shadow
    *fetchInsGroupList(_,{ call, put, select }) {
      const adjustInfo = yield select(state => state.adjustaccu);
      const areaId = adjustInfo.updateBaseInfo.cityId;
      const { custId } = adjustInfo;
      const response = yield call(getInsGroupList, { custId, areaId, pdId: 'PDINF_0000000002' });
      if (response.success) {
        if (response.data) {
          yield put({
            type: 'updateModelData',
            payload: {
              insGroupList: response.data,
            },
          });
        } else {
          message.warning('该地区下未维护公积金组合');
        }
      } else {
        message.warning(response.message || '获取公积金组合列表：服务端错误');
      }
    },
    // 提交数据
    submit:[
      function* ({ payload }, { call, put, select }) {
      const adjustInfo = yield select(state => state.adjustaccu);
      const { sendId, insIdeFlag, accuWageFlag, accuLocFlag } = adjustInfo;
      let submitData = {
        sendId,
        insIdeFlag,
        accuWageFlag,
        accuLocFlag,
        updateAccuDecWage: {},
        adjLocPkgDto: {},
      };
      const temp = payload;
      delete temp.values.insGroupTable;
      Object.entries(payload.values).forEach(([key, value]) => {
        if (key === 'beginDate') {
          submitData[key] = value && value.format('YYYY-MM-01');
        } else if (key === 'accuWageFlag' && value) {
          // 修改工资
          submitData.updateAccuDecWage = payload.values.updateAccuDecWage;
        } else if (key === 'accuLocFlag' && value) {
          // 修改社保组合
          submitData.adjLocPkgDto = {
            accoId:
              (payload.values.accoId && payload.values.accoId.key) ||
              (payload.values.bigAccoId && payload.values.bigAccoId.key) ||
              '',
            grpId: (payload.values.grpId && payload.values.grpId.key) || '',
            payWay: (payload.values.payWay && payload.values.payWay.key) || '',
            serSetId:
              adjustInfo.insSerConfigFlag === '1'
                ? payload.values.serSetId && payload.values.serSetId.key
                : '',
          };
        }
      });
      submitData = payload.adjId ? { ...submitData, adjId: payload.adjId } : submitData;
      const response = yield call(payload.adjId ? updateAccuSubmit : accuSubmit, submitData);
      if (response.success) {
        message.success(payload.adjId ? '保存成功!' : '操作成功！');
        yield put(
          routerRedux.push({
            pathname: payload.adjId
              ? '/customservicemanage/adjusttask/index'
              : '/customservicemanage/adjusttask/adjustfinish',
          })
        );
      } else {
        message.warning(`${response.message || '保存失败！'}`);
      }
    },
    { type:'throttle',ms:10000 }
  ],
  },

  reducers: {
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        data: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 问题人员详情
    getProDetail(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbkList,
        probId: payload.probId,
      };
    },
    // 单个调整：雇员姓名
    getEmpNameList(state, { payload }) {
      return {
        ...state,
        empNameList: payload,
      };
    },
  },
};
